<template>
    <div class=" p-4">
        <el-form>
            <el-row :gutter="20" class="mb-4">
                <el-col :span="6">
                    <el-form-item label="选择日期">
                        <el-date-picker v-model="dateRange" type="daterange" range-separator="~"
                            start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" style="width: 100%;" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="一级目录">
                        <el-select v-model="filters.firstLevel" filterable remote reserve-keyword clearable
                            placeholder="选择一级目录" :loading="loading" :remote-method="remoteMethodF" @change="changeF"
                            style="width: 240px">
                            <el-option v-for="item in optionsF" :key="item.id" :label="item.name" :value="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="二级目录">
                        <el-select v-model="filters.secondLevel" filterable remote reserve-keyword clearable
                            :disabled="filters.firstLevel == '' || filters.categoryName != ''" placeholder="选择二级目录"
                            :loading="loading" style="width: 240px">
                            <el-option v-for="item in optionsS" :key="item.id" :label="item.name" :value="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="品类名称">
                        <el-select v-model="filters.categoryName" filterable remote reserve-keyword clearable
                            placeholder="选择品类" :loading="loading" :remote-method="remoteMethodC" @change="changeC"
                            style="width: 240px">
                            <el-option v-for="item in optionsC" :key="item.id" :label="item.categoryName"
                                :value="item.categoryName" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-row>
            <el-col :span="24" class="text-right">
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button type="primary" @click="handleExport">导出</el-button>
            </el-col>
        </el-row>


        <!-- Table -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="70" />
            <el-table-column prop="categoryName" label="品类名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="date" label="维护日期" />
            <el-table-column prop="purchasePrice" label="单价" />
            <el-table-column prop="totalPrice" label="总价" />
            <el-table-column prop="vendor" label="供应商" />
        </el-table>

        <!-- Pagination -->
        <div class="flex justify-between items-center mt-4">
            <span class="text-sm text-gray-500">
                共 {{ total }} 条记录 第 {{ currentPage }} / {{ totalPages }} 页
            </span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15]"
                :small="small" :disabled="disabled" :background="background"
                layout="total, prev, pager, next, sizes, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getInoutinventoryPage, getLevelFirst, searchLevel, findAllCategory } from '@/utils/category'

// Data
const dateRange = ref([new Date().toLocaleDateString().replace(/\//g, '-'), new Date().toLocaleDateString().replace(/\//g, '-')])
const filters = ref({
    firstLevel: '',
    secondLevel: '',
    categoryName: '',
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(400)
const loading = ref(false)
const optionsF = ref([])
const tableData = ref([])
const optionsS = ref([])
const optionsC = ref([])

// Computed
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

onMounted(() => {
    search()
})
// Methods
const search = () => {
    getInoutinventoryPage({ firstLevel: filters.value.firstLevel, secondLevel: filters.value.secondLevel, categoryName: filters.value.categoryName, startTime: dateRange.value ? dateRange.value[0] : '', endTime: dateRange.value ? dateRange.value[1] : '' }, currentPage.value, pageSize.value).then(res => {
        if (res.code == 200) {
            tableData.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error(res.message)
        }
    })
}

// Methods
const handleQuery = () => {
    search()
}

const handleExport = () => {
    window.location.href = `/api/inoutinventory/inoutpriceexport/?firstLevel=${filters.value.firstLevel}&secondLevel=${filters.value.secondLevel}&categoryName=${filters.value.categoryName}&startTime=${dateRange.value ? dateRange.value[0] : ''}&endTime=${dateRange.value ? dateRange.value[1] : ''}`
}

const handleSizeChange = (val) => {
    pageSize.value = val
    search()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    search()
}

const remoteMethodF = (query) => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        getLevelFirst().then(res => {
            if (res.code == 200) {
                optionsF.value = res.data.filter((item) => {
                    return item.name.toLowerCase().includes(query.toLowerCase())
                })
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}

const changeF = () => {
    filters.value.secondLevel = ''
    searchLevel({ name: filters.value.firstLevel }).then(res => {
        if (res.code == 200) {
            optionsS.value = res.data[0].children
        } else {
            ElMessage.error(res.message)
        }
    })
}

const changeC = (name) => {
    optionsC.value.forEach(element => {
        if (element.categoryName == name) {
            filters.value.firstLevel = element.firstLevel
            filters.value.secondLevel = element.secondLevel
        }
    });
    searchLevel({ name: filters.value.firstLevel }).then(res => {
        if (res.code == 200) {
            optionsS.value = res.data[0].children
        } else {
            ElMessage.error(res.message)
        }
    })
}

const remoteMethodC = (query) => {
    loading.value = true
    setTimeout(() => {
        findAllCategory({ firstLevel: filters.value.firstLevel, secondLevel: filters.value.secondLevel, categoryName: query }).then(res => {
            if (res.code == 200) {
                loading.value = false
                optionsC.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}
</script>

<style scoped>
.el-pagination {
    float: right;
}
</style>